package skills.jssvc.deu.cn.skillsecond.programming5;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import skills.jssvc.deu.cn.skillsecond.MyApplication;
import skills.jssvc.deu.cn.skillsecond.R;
import skills.jssvc.deu.cn.skillsecond.bean.AllSense;
import skills.jssvc.deu.cn.skillsecond.util.HttpRequest;
import skills.jssvc.deu.cn.skillsecond.util.SqlHelper;


public class EnvironmentalFragment extends Fragment {
    private View view;
    private TextView indexTv1;
    private TextView indexTv2;
    private TextView indexTv3;
    private TextView indexTv4;
    private TextView indexTv5;
    private TextView indexTv6;
    private RelativeLayout layout1,layout2,layout3,layout4,layout5,layout6;
    private int temp,hum,light,co2,pm,roadState;
    private SqlHelper helper;
    private SQLiteDatabase db;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_environmental, container, false);
        initView();
        if(isAdded()){
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    initData();
                }
            },0,3*1000);
        }
        return view;
    }

    private void initView(){
        indexTv1 = (TextView) view.findViewById(R.id.frag5_envir_index1_tv);
        indexTv2 = (TextView) view.findViewById(R.id.frag5_envir_index2_tv);
        indexTv3 = (TextView) view.findViewById(R.id.frag5_envir_index3_tv);
        indexTv4 = (TextView) view.findViewById(R.id.frag5_envir_index4_tv);
        indexTv5 = (TextView) view.findViewById(R.id.frag5_envir_index5_tv);
        indexTv6 = (TextView) view.findViewById(R.id.frag5_envir_index6_tv);
        layout1 = (RelativeLayout)view.findViewById(R.id.frag5_envir_index1_layout);
        layout2 = (RelativeLayout)view.findViewById(R.id.frag5_envir_index2_layout);
        layout3 = (RelativeLayout)view.findViewById(R.id.frag5_envir_index3_layout);
        layout4 = (RelativeLayout)view.findViewById(R.id.frag5_envir_index4_layout);
        layout5 = (RelativeLayout)view.findViewById(R.id.frag5_envir_index5_layout);
        layout6 = (RelativeLayout)view.findViewById(R.id.frag5_envir_index6_layout);
        temp = PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("temp",20);
        hum = PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("hum",20);
        light = PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("light",20);
        co2 = PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("co2",20);
        pm = PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("pm",20);
        roadState = PreferenceManager.getDefaultSharedPreferences(getContext()).getInt("roadstate",2);
    }

    private void initData() {
        final ContentValues values = new ContentValues();
        HttpRequest.post("GetAllSense", "{\"UserName\":\"user1\"}", new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                AllSense allSense = new Gson().fromJson(jsonObject.toString(), AllSense.class);
                indexTv1.setText(String.valueOf(allSense.getTemperature()));
                indexTv2.setText(String.valueOf(allSense.getHumidity()));
                indexTv3.setText(String.valueOf(allSense.getLightIntensity()));
                indexTv4.setText(String.valueOf(allSense.getCo2()));
                indexTv5.setText(String.valueOf(allSense.getPm()));
                if(allSense.getTemperature() > temp){
                    layout1.setBackgroundColor(Color.RED);
                }else {
                    layout1.setBackgroundColor(Color.GREEN);
                }
                if(allSense.getHumidity() > hum){
                    layout2.setBackgroundColor(Color.RED);
                }else {
                    layout2.setBackgroundColor(Color.GREEN);
                }
                if(allSense.getLightIntensity() > light){
                    layout3.setBackgroundColor(Color.RED);
                }else {
                    layout3.setBackgroundColor(Color.GREEN);
                }
                if(allSense.getCo2() > co2){
                    layout4.setBackgroundColor(Color.RED);
                }else {
                    layout4.setBackgroundColor(Color.GREEN);
                }
                if(allSense.getPm() > pm){
                    layout5.setBackgroundColor(Color.RED);
                }else {
                    layout5.setBackgroundColor(Color.GREEN);
                }
                values.put("tem",allSense.getTemperature());
                values.put("hum",allSense.getHumidity());
                values.put("light",allSense.getLightIntensity());
                values.put("co2",allSense.getCo2());
                values.put("pm",allSense.getPm());
                HttpRequest.post("GetRoadStatus", "{\"RoadId\":1,\"UserName\":\"user1\"}", new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            int state = jsonObject.getInt("Status");
                            if(state>roadState){
                                layout6.setBackgroundColor(Color.RED);
                            }else {
                                layout6.setBackgroundColor(Color.GREEN);
                            }
                            indexTv6.setText(String.valueOf(state));
                            values.put("roadState",state);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },null);
            }
        },null);
        values.put("time",new SimpleDateFormat("mm:ss").format(new Date(System.currentTimeMillis())));
        storage(values);
    }

    private void storage(ContentValues values){
        if(values!=null){
            helper = new SqlHelper(MyApplication.appContext, SqlHelper.DA_NAME, null, 1);
            db = helper.getWritableDatabase();
            Cursor cursor = db.rawQuery("select * from " + SqlHelper.ALLSENSE, null);
            if(cursor.getCount()>20){
                for(int i=0;i<cursor.getCount()-20;i++){
                    Cursor cursor1 = db.rawQuery("select * from " + SqlHelper.ALLSENSE, null);
                    if(cursor1.moveToFirst()){
                        db.delete(SqlHelper.ALLSENSE,"id = ?",new String[]{cursor1.getString(cursor1.getColumnIndex("id"))});
                        Log.d("TAG", "storage: cursorid="+cursor1.getString(cursor1.getColumnIndex("id")));
                    }
                    cursor1.close();
                }
                db.insert(SqlHelper.ALLSENSE, null, values);
                cursor.close();
            }else {
                db.insert(SqlHelper.ALLSENSE, null, values);
            }
            db.close();
        }
    }

}
